package cn.vawn.medical.controller;

import cn.vawn.base.consts.Contants;
import cn.vawn.base.controller.BaseController;
import cn.vawn.base.dto.ReturnMsg;
import cn.vawn.base.dto.UserInfo;
import cn.vawn.base.util.DateUtil;
import cn.vawn.base.util.JsonUtil;
import cn.vawn.base.util.StringUtil;
import cn.vawn.base.util.UuidUtil;
import cn.vawn.medical.entity.NormalUser;
import cn.vawn.medical.service.INormalUserService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("normalUser")
@Controller
public class NormalUserController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(NormalUserController.class);

    @Autowired
    private INormalUserService normalUserService;

    @RequestMapping("weixinRegist")
    public @ResponseBody
    ReturnMsg regist(HttpServletRequest request, HttpServletResponse response, @RequestBody String body){
        ReturnMsg msg = new ReturnMsg();
        Date now = new Date();
        if (StringUtil.notEmpty(body)){
            JSONObject jsonObject = JSONObject.fromObject(body);

            String username = (String) jsonObject.get("username");
            String phone = (String) jsonObject.get("phone");
            String password = (String) jsonObject.get("password");
            if(StringUtil.notEmpty(password)){
                password = new BCryptPasswordEncoder().encode(password);
            }
            String birthDay = (String) jsonObject.get("birthDay");
            String identityCard = (String) jsonObject.get("identityCard");
            String sex = (String) jsonObject.get("sex");
            String openid = (String) jsonObject.get("openid");
            String weiXinUserInfoJson = (String) jsonObject.get("weiXinUserInfo");
            //check user
            Map<String, Object> map = new HashMap<>();

            map.put("openid", openid);
            NormalUser dbNormalUser = normalUserService.getNormalUserByCondition(map);
            if (dbNormalUser != null){
                msg.addErrorMsg("此微信号已经注册");
            }else {
                String secret = UuidUtil.getUuid();
                if (StringUtil.notEmpty(weiXinUserInfoJson)){
                    UserInfo userInfo = JsonUtil.fromJson(weiXinUserInfoJson, UserInfo.class);
                    String nickName = "";
                    String nickNameStr = "" ;
                    try {
                        nickNameStr = userInfo.getNickname();
                        InputStream inputStream = new ByteArrayInputStream(
                                nickNameStr.getBytes("ISO-8859-1"));
                        InputStreamReader inputStreamReader = new InputStreamReader(
                                inputStream, "UTF-8");
                        BufferedReader bufferedReader = new BufferedReader(
                                inputStreamReader);
                        String str = null;
                        StringBuffer buffer = new StringBuffer();
                        while ((str = bufferedReader.readLine()) != null) {
                            buffer.append(str);
                        }
                        nickName = buffer.toString();
                    } catch (Exception e) {
                        msg.addErrorMsg("昵称解析错误");
                    }
                    logger.info("nickNameStr : " + nickNameStr);
                    logger.info("nickName : " + nickName);
                    NormalUser normalUser = new NormalUser(username,userInfo.getOpenid(),nickName ,userInfo.getHeadimgurl(),userInfo.getSex(),
                            phone,identityCard,password, DateUtil.parseDate(birthDay), Contants.COMMON_USER_TYPE,now,now,secret);
                    normalUserService.insertNormalUser(normalUser);
                    msg.setErrorCode(Contants.SUCCESS);
                }else {
                    msg.addErrorMsg("信息异常");
                }
            }
        }else {
            msg.addErrorMsg("传参解析异常");
        }

        return msg;
    }

    @RequestMapping(value = "weixinLogin", method = {RequestMethod.POST})
    public @ResponseBody
    ReturnMsg weixinLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody String body){
        ReturnMsg msg = new ReturnMsg();
        Date now = new Date();
        if (StringUtil.notEmpty(body)){

            JSONObject jsonObject = JSONObject.fromObject(body);

            String type = (String) jsonObject.get("type");
            String phone = (String) jsonObject.get("phone");
            String password = (String) jsonObject.get("password");
            String identityCard = (String) jsonObject.get("identityCard");
            //check user
            Map<String, Object> map = new HashMap<>();
            NormalUser dbNormalUser = null;
            if ("username".equals(type)){
                map.put("idCard", identityCard);
                dbNormalUser = normalUserService.getNormalUserByCondition(map);
                if (dbNormalUser == null){
                    msg.addErrorMsg("用户不存在");
                }else {
                    String password1 = dbNormalUser.getPassword();
                    boolean matches = new BCryptPasswordEncoder().matches(password, password1);
                    if (matches){
                        msg.setData(dbNormalUser);
                        msg.setErrorCode(Contants.SUCCESS);
                    }else {
                        msg.addErrorMsg("账号或密码不正确");
                    }
                }
            }else if ("phone".equals(type)){
                map.put("mobile", phone);
                dbNormalUser = normalUserService.getNormalUserByCondition(map);
                if (dbNormalUser == null){
                    msg.addErrorMsg("用户不存在");
                }else {
                    msg.setData(dbNormalUser);
                    msg.setErrorCode(Contants.SUCCESS);
                }
            }else {
                msg.addErrorMsg("登陆异常");
            }
        }else {
            msg.addErrorMsg("数据传递异常");
        }
        return msg;
    }

    @RequestMapping("weixinLoadUserByPhone")
    public @ResponseBody
    ReturnMsg weixinLoadUserByPhone(HttpServletRequest request, HttpServletResponse response, @RequestBody String body){
        ReturnMsg msg = new ReturnMsg();
        if (StringUtil.notEmpty(body)){
            JSONObject jsonObject = JSONObject.fromObject(body);

            String conditionType = (String) jsonObject.get("conditionType");
            Map<String, Object> map = new HashMap<>();
            if ("openid".equals(conditionType)){
                String openid = (String) jsonObject.get("openid");
                if(StringUtil.notEmpty(openid)){
                    map.put("openid", openid);
                }else {
                    msg.addErrorMsg("请先输入手机号");
                }
            }else if ("phone".equals(conditionType)){
                String phone = (String) jsonObject.get("phone");
                if(StringUtil.notEmpty(phone)){
                    map.put("mobile", phone);
                }else {
                    msg.addErrorMsg("请先输入手机号");
                }
            }
            if (msg.isValid()){
                NormalUser dbNormalUser = normalUserService.getNormalUserByCondition(map);
                if (dbNormalUser != null){
                    msg.setData(dbNormalUser);
                    msg.setErrorCode(Contants.SUCCESS);
                }else {
                    msg.addErrorMsg("此手机号未注册用户，请先注册");
                }
            }
        }else {
            msg.addErrorMsg("传参解析异常");
        }
        return msg;
    }

    @RequestMapping("weixinResetPs")
    public @ResponseBody
    ReturnMsg weixinResetPs(HttpServletRequest request, HttpServletResponse response, @RequestBody String body){
        ReturnMsg msg = new ReturnMsg();
        Date now = new Date();
        if (StringUtil.notEmpty(body)) {
            JSONObject jsonObject = JSONObject.fromObject(body);
            String phone = (String) jsonObject.get("phone");
            String type = (String) jsonObject.get("type");

            if(StringUtil.notEmpty(phone)){
                Map<String, Object> map = new HashMap<>();
                map.put("mobile", phone);
                NormalUser dbNormalUser = normalUserService.getNormalUserByCondition(map);
                if (dbNormalUser != null){
                    if ("password".equals(type)){
                        String password = (String) jsonObject.get("password");
                        password = new BCryptPasswordEncoder().encode(password);
                        dbNormalUser.setPassword(password);
                    }else if("phone".equals(type)){
                        String newPhone = (String) jsonObject.get("newPhone");
                        dbNormalUser.setMobile(newPhone);
                    }else if("sex".equals(type)){
                        Integer sex = (Integer) jsonObject.getInt("sex");
                        dbNormalUser.setSex(sex);
                    }else if ("birthday".equals(type)){
                        String birthday = (String) jsonObject.get("birthday");
                        dbNormalUser.setBirthday(DateUtil.parseDate(birthday));
                    }
                    dbNormalUser.setUpdatedBy(1);
                    dbNormalUser.setUpdatedTime(new Date());
                    normalUserService.updateNormalUser(dbNormalUser);
                    msg.setData(dbNormalUser.getMobile());
                    msg.setErrorCode(Contants.SUCCESS);
                }else {
                    msg.addErrorMsg("此手机号未注册用户，请先注册");
                }
            }else {
                msg.addErrorMsg("请先输入手机号");
            }
        }else {
            msg.addErrorMsg("传参解析异常");
        }
        return msg;
    }
}